﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;

using System.ComponentModel;
using ecdl.demo.model.util;

namespace ecdl.demo.model.util {
    public interface ITestTimer {
        event EventHandler<GenericEventArgs<TimeSpan>> TimeUpdateEvent;
        event EventHandler TimerFinishedEvent;

        TimerState TimerState { get; set; }

        void Start();
        void Stop();

        void Pause();
        void Resume();
    }

    public enum TimerState {
        Stopped,
        Running,
        Paused
    }

    public class StandardTestTimer : ITestTimer {

        private static readonly int INTERVAL = 300;
        private static readonly int AVAILABLE_TIME_SECS = 45 * 60;

        private Timer timer = new Timer(INTERVAL);
        private TimeSpan remainingTime;

        public event EventHandler<GenericEventArgs<TimeSpan>> TimeUpdateEvent;

        public event EventHandler TimerFinishedEvent;

        public StandardTestTimer() {
            TimerState = util.TimerState.Stopped;
            timer.AutoReset = true;
            timer.Elapsed += new ElapsedEventHandler(TimerTick);
            remainingTime = new TimeSpan(0, 0, AVAILABLE_TIME_SECS);
        }

        void TimerTick(object sender, ElapsedEventArgs e) {
            remainingTime = remainingTime.Subtract(new TimeSpan(0,0,0,0, INTERVAL));
            FireTimeUpdateEvent();
        }

        private void FireEvent(EventHandler Event, EventArgs eventArgs) {
            if (Event != null) {
                Event(this, EventArgs.Empty);
            }
        }

        public void Start() {
            FireTimeUpdateEvent();
            TimerState = util.TimerState.Running;
            timer.Start();
        }

        private void FireTimeUpdateEvent() {
            if (TimeUpdateEvent != null) {
                TimeUpdateEvent(this, new GenericEventArgs<TimeSpan>(remainingTime));

                
            }
        }
        
        public void Stop() {
            timer.Stop();
            TimerState = util.TimerState.Stopped;
            TimerState = TimerState.Stopped;
        }

        DateTime pauseTime;

        public void Pause() {
            if (TimerState == util.TimerState.Running) {
                timer.Stop();
                pauseTime = DateTime.Now;
                TimerState = util.TimerState.Paused;
            }
        }

        public void Resume() {
            if (TimerState == util.TimerState.Paused) {
                timer.Start();
                TimerState = util.TimerState.Running;
            }
        }

        public TimerState TimerState {
            get;
            set;
        }

    }
}
